package logic

import (
	"context"
	"fmt"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"order_srv/global"
	"order_srv/internal/model"

	uuid "github.com/satori/go.uuid"
	"github.com/zeromicro/go-zero/core/logx"
	"order_srv/internal/svc"
	"order_srv/order"
)

type CreateOrderLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateOrderLogic {
	return &CreateOrderLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateOrderLogic) CreateOrder(in *order.OrderInfoRequest) (*order.OrderInfoResponse, error) {
	// todo: add your logic here and delete this line
	//创建订单
	orderInfo := model.Order{
		UserId:  int(in.UserId),
		CarId:   int(in.CarId),
		OrderSn: fmt.Sprintf("%s", uuid.NewV4()),
		Status:  "WAIT_BUYER_PAY",
		Price:   in.Price,
	}
	tx := global.DB.Create(&orderInfo)
	if tx.RowsAffected == 0 {
		return nil, status.Errorf(codes.Internal, "创建订单失败失败")
	}
	return &order.OrderInfoResponse{
		Id:      int32(orderInfo.ID),
		UserId:  int32(orderInfo.UserId),
		CarId:   int32(orderInfo.CarId),
		OrderSn: orderInfo.OrderSn,
		Status:  orderInfo.Status,
		TradeNo: orderInfo.TradeNo,
		Price:   orderInfo.Price,
		PayType: int32(orderInfo.PayType),
	}, nil
}
